/**
  ******************************************************************************
  * @brief        STM32F103 BootLoader
  *
  * Copyright (c) 2021, <1148138800@qq.com>
  *
  * SPDX-License-Identifier: Apache-2.0
  *
  * Change Logs: 
  * Date           Author       Notes 
  * 2021-09-21     zhangql      Initial version. 
******************************************************************************/	
//e.g : STM32F103C8T6  ->64K


#include "update.h"
#include "stm32f1xx_hal.h"


__asm void MSR_MSP(uint32_t addr)
{
    MSR MSP, r0
    BX r14;
}

/**
 * @param  app_address    address to jump 
 * @return null        
 */
void Ctrl_Program_Jump(unsigned int app_address)
{
    unsigned int JumpAddress = 0;
    pFunction Jump_To_Application;
    
    if (((*(__IO unsigned int*)app_address) & 0x2FFE0000 ) == 0x20000000)
    { 
        /* Jump to user application */
        JumpAddress = *(__IO unsigned int*) (app_address + 4);
        Jump_To_Application = (pFunction) JumpAddress;

        /* Initialize user application's Stack Pointer */
        __set_MSP(*(__IO unsigned int*) app_address);

        /* Jump to application */
        Jump_To_Application();
    }
}

/**
 * @param  null
 * @return null
 * @note   put this function in the main loop
 */
void Select_App_Address()
{
	unsigned int ulAppFlag = 0;
	unsigned int  PageError  = 0;
	FLASH_EraseInitTypeDef  FLASH_EraseInitStruct =
	{
		.TypeErase = FLASH_TYPEERASE_PAGES,
		.NbPages = 1,/*Number of pages */
		.Banks = FLASH_BANK_1,
		.PageAddress = APP_SELECT_ADDRESS/* The starting address of the erased page*/
	};
  __disable_irq();
	ulAppFlag = *(unsigned int *)APP_SELECT_ADDRESS;
	switch(ulAppFlag)
	{
			case 0xFFFFFFFFU:
			{
					HAL_FLASH_Unlock();
					HAL_FLASHEx_Erase(&FLASH_EraseInitStruct, &PageError );
					HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, APP_SELECT_ADDRESS, 0x01);
					HAL_FLASH_Lock();
					break;
			}
			case 0x00000001U:
			{
					Ctrl_Program_Jump(APP1_ADDRESS);
					break;
			}
			case 0x00000002U:
			{
					Ctrl_Program_Jump(APP2_ADDRESS);
					break;
			}
			default:
			{
					break;
			}
	}
}

